package com.bdqn.shequ.modules.sys.controller;

import com.bdqn.shequ.ExcelUtil.FileUtil;
import com.bdqn.shequ.common.annotation.SysLog;
import com.bdqn.shequ.common.utils.PageUtils;
import com.bdqn.shequ.common.utils.R;
import com.bdqn.shequ.common.validator.ValidatorUtils;
import com.bdqn.shequ.common.validator.group.AddGroup;
import com.bdqn.shequ.common.validator.group.UpdateGroup;
import com.bdqn.shequ.modules.sys.entity.SysUserEntity;
import com.bdqn.shequ.modules.sys.entity.TcMemberEntity;
import com.bdqn.shequ.modules.sys.entity.TcMessageEntity;
import com.bdqn.shequ.modules.sys.service.TcMemberService;
import com.bdqn.shequ.modules.sys.service.TcMessageService;
import com.bdqn.shequ.modules.sys.utils.test;
import org.apache.poi.hssf.usermodel.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 会员表
 *
 * @author Mark
 * @email sunlightcs@gmail.com
 * @date 2019-04-12 11:02:59
 */
@RestController
@RequestMapping("sys/tcmember")
public class TcMemberController {
    @Autowired
    private TcMemberService tcMemberService;

    @Autowired
    private TcMessageService tcMessageService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:tcmember:list")
    public R list(@RequestParam Map<String, Object> params){

        PageUtils page = tcMemberService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sys:tcmember:info")
    public R info(@PathVariable("id") Long id){
        TcMemberEntity tcMember = tcMemberService.getById(id);

        return R.ok().put("tcMember", tcMember);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("sys:tcmember:save")
    public R save(@RequestBody TcMemberEntity tcMember){
        ValidatorUtils.validateEntity(tcMember, AddGroup.class);
        if(tcMember.getTotalIntegral()>5000){
            tcMember.setMemberLevel(5L);
        }else if(tcMember.getTotalIntegral()>4000&&tcMember.getTotalIntegral()<=5000){
            tcMember.setMemberLevel(4L);
        }else if(tcMember.getTotalIntegral()>3000&&tcMember.getTotalIntegral()<=4000){
            tcMember.setMemberLevel(3L);
        }else if(tcMember.getTotalIntegral()>2000&&tcMember.getTotalIntegral()<=3000){
            tcMember.setMemberLevel(2L);
        }else if(tcMember.getTotalIntegral()>1000&&tcMember.getTotalIntegral()<=2000){
            tcMember.setMemberLevel(1L);
        }else{
            tcMember.setMemberLevel(0L);
        }

        Date getDate = Calendar.getInstance().getTime();
        tcMember.setMemberCardNo((Long.valueOf(tcMember.getMemberEmail().substring(0, tcMember.getMemberEmail().indexOf("@"))+ new SimpleDateFormat("yyyyMMdd").format(getDate))).toString());
        tcMember.setCreateTime(getDate);
        tcMember.setRegisterTime(getDate);
        if(tcMember.getMemberType().equals("GUEST")){
            tcMember.setMemberStatus("GUEST");
        }

        tcMemberService.save(tcMember);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("sys:tcmember:update")
    public R update(@RequestBody TcMemberEntity tcMember){
        ValidatorUtils.validateEntity(tcMember, UpdateGroup.class);
        Date getDate = Calendar.getInstance().getTime();
        tcMember.setUpdateTime(getDate);
        if(tcMember.getMemberType().equals("REGULAR_MEMBER")){
            tcMember.setMemberStatus("REGISTER_SUCCESS");
        }else if(tcMember.getMemberType().equals("VERIFIED_MEMBER")){
            tcMember.setMemberStatus("VERIFY_SUCCESS");
        }else{
            tcMember.setMemberStatus("GUEST");
        }

        if(tcMember.getTotalIntegral()>5000){
            tcMember.setMemberLevel(5L);
        }else if(tcMember.getTotalIntegral()>4000&&tcMember.getTotalIntegral()<=5000){
            tcMember.setMemberLevel(4L);
        }else if(tcMember.getTotalIntegral()>3000&&tcMember.getTotalIntegral()<=4000){
            tcMember.setMemberLevel(3L);
        }else if(tcMember.getTotalIntegral()>2000&&tcMember.getTotalIntegral()<=3000){
            tcMember.setMemberLevel(2L);
        }else if(tcMember.getTotalIntegral()>1000&&tcMember.getTotalIntegral()<=2000){
            tcMember.setMemberLevel(1L);
        }else{
            tcMember.setMemberLevel(0L);
        }
        tcMemberService.updateById(tcMember);
        
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:tcmember:delete")
    public R delete(@RequestBody Long[] ids){
        tcMemberService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 认证
     */
    @SysLog("认证")
    @RequestMapping("/shenhe")
    public R renzheng(String id, String statu1, String statu2, String phone, String smstext, HttpSession session){

        test test1 = new test();
        boolean isRight=test1.xinxi(smstext,phone);

        if(isRight){
            boolean flag = tcMemberService.updateStatus(Long.parseLong(id),statu1,statu2);
            if(!flag){
                return R.error("认证失败");
            }

            SysUserEntity user=(SysUserEntity)session.getAttribute("loginuser");
            TcMessageEntity tcMessage = new TcMessageEntity();
            tcMessage.setMessageReceivertelephone(phone);
            tcMessage.setMessageSituation("CERTIFICATION_AUDIT");
            tcMessage.setNoticeContent(smstext);
            tcMessage.setCreateTime(new Date());
            tcMessage.setUpdateUser(user.getUserId());
            tcMessage.setCreateUser(user.getUserId());

            tcMessageService.save(tcMessage);
            return R.ok();
        }else {
            return R.error("短信条数不足，无法发送！");
        }

    }

    /*
    *导出表格
    */
    @RequestMapping("/exportExcel")
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
        List<TcMemberEntity> userList = tcMemberService.list();
        //声明一个工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();

        //生成一个表格，设置表格名称
        HSSFSheet sheet = workbook.createSheet("会员用户表");
        //设置表格列宽度
        sheet.setDefaultColumnWidth(15);

        //写入List<List<String>>中的数据
        int rowIndex = 0;


            //遍历添加本行数据
            for (int i = 0; i < userList.size(); i++) {

                HSSFRow row = sheet.createRow(rowIndex++);
                //创建一个单元格
                HSSFCell cell = row.createCell(i);

                //创建一个内容对象
                HSSFRichTextString text = new HSSFRichTextString(userList.get(i).getRealName());

                //将内容对象的文字内容写入到单元格中
                cell.setCellValue(text);
            }

        //准备将Excel的输出流通过response输出到页面下载
        //八进制输出流
        response.setContentType("application/octet-stream");

        //设置导出Excel的名称
        response.setHeader("Content-disposition", "attachment;filename=" + "ExcelTest.xls");

        //刷新缓冲
        try{
            response.flushBuffer();

            //workbook将Excel写入到response的输出流中，供页面下载该Excel文件
            workbook.write(response.getOutputStream());

            //关闭workbook
            workbook.close();
        }catch (Exception e){
            e.getMessage();
        }

    }

}

